package com.sqpoll.android;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.sqpoll.android.poll.Poll;
import com.sqpoll.android.poll.PollCreateActivity;
import com.sqpoll.android.poll.PollDetailActivity;
import com.sqpoll.android.poll.PollListAdapter;
import com.sqpoll.android.settings.SettingsActivity;
import com.sqpoll.android.widget.PullToRefreshListView;
import com.sqpoll.android.widget.PullToRefreshListView.OnRefreshListener;

/**
 * The fragment for open poll list.
 * 
 * @author Younggue Bae
 */
public class OpenPollListFragment extends SherlockFragment {

	public static final String TAG = "OpenPollListFragment";
	
	private PullToRefreshListView mListView;
	private PollListAdapter mAdapter;
	private LayoutInflater mInflater;
	private boolean mLockListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	@Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_open_poll_list, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_open_poll_list, container, false);

		// for dynamic list view
		List<Poll> items = loadItems();
		mLockListView = false;
		mAdapter = new PollListAdapter(getActivity(), R.layout.list_item_poll, items);
		mListView = (PullToRefreshListView) view.findViewById(R.id.list_view);
		
		mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mListView.addFooterView(mInflater.inflate(R.layout.dynamic_loading_list_footer, null));

		mListView.setOnRefreshListener(mRefreshListener);
		mListView.setOnItemClickListener(mItemClickListener);
		mListView.setOnScrollListener(mScrollListener);
		mListView.setAdapter(mAdapter);
		
		return view;
	}

	OnRefreshListener mRefreshListener = new OnRefreshListener() {
		@Override
		public void onRefresh() {
			// Your code to refresh the list contents

			// ...

			// Make sure you call listView.onRefreshComplete()
			// when the loading is done. This can be done from here or any
			// other place, like on a broadcast receive from your loading
			// service or the onPostExecute of your AsyncTask.

			mListView.onRefreshComplete();
		}
	};

	OnItemClickListener mItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			Poll currentItem = (Poll) mAdapter.getItem(position);
			String question = currentItem.getQuestion();
			//Toast.makeText(getActivity(), "Selected : " + question, Toast.LENGTH_SHORT).show();
			
			Intent intent = new Intent(getActivity(), PollDetailActivity.class);
			intent.putExtra("id", "test");
			intent.putExtra("type", "open");
			intent.putExtra("question", question);
			startActivity(intent);
		}
	};
	
	OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView v, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			int count = totalItemCount - visibleItemCount;			
			//Log.i(TAG, "count == " + count + ", firstVisibleItem == " + firstVisibleItem);

			if(firstVisibleItem >= count && totalItemCount != 0 && mLockListView == false) {
				Toast.makeText(getActivity(), "Loading next items", Toast.LENGTH_SHORT).show();
				Log.i(TAG, "Loading next items");
				addItems(5);
			}
		}
	};
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		Log.v(TAG, "Selected option item = " + item.getTitle());

		switch (item.getItemId()) {
		case R.id.menu_new_poll:
			//Toast.makeText(getActivity(), "Selected: New poll", Toast.LENGTH_SHORT).show();
			Intent intentPollCreate = new Intent(getActivity(), PollCreateActivity.class);
			getActivity().startActivity(intentPollCreate);
			break;
			
		case R.id.menu_my_polls_onwork:
			Toast.makeText(getActivity(), "Selected: My polls on work", Toast.LENGTH_SHORT).show();
			break;
			
		case R.id.menu_my_open_polls:
			Toast.makeText(getActivity(), "Selected: My open polls", Toast.LENGTH_SHORT).show();
			break;

		case R.id.menu_settings:
			//Toast.makeText(getActivity(), "Selected: Settings", Toast.LENGTH_SHORT).show();
			Intent intentSettings = new Intent(getActivity(), SettingsActivity.class);
			getActivity().startActivity(intentSettings);
			break;
		}

		return true;
	}
	
	private List<Poll> loadItems() {
		Resources res = getResources();

		List<Poll> items = new ArrayList<Poll>();

		Poll item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_3));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?_1");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_5));
		item.setUsername("Younggue Bae");
		item.setCreateDate("06.07");
		item.setStatus("open");
		item.setQuestion("Do you like this news?_2");
		item.setCommentCount(5);
		item.setVoterCount(10);
		
		items.add(item);
		
		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_6));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?_3");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_9));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?_4");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_10));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?_5");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		return items;
	}
	
	private void addItems(final int size) {
		// Set lock to prevent from calling repeatedly.
		mLockListView = true;
		
		Runnable run = new Runnable() {
			@Override
			public void run() {
				for(int i = 0 ; i < size ; i++) {
					Poll item = new Poll();
					item.setPollImage(getResources().getDrawable(R.drawable.ic_3));
					item.setUsername("Sonya Cho");
					item.setCreateDate("1 day ago");
					item.setStatus("open");
					item.setQuestion("Do you like this food?...");
					item.setCommentCount(10);
					item.setVoterCount(17);
					
					mAdapter.addItem(item);
				}
				
				// After finishing loading, notifies adapter and releases the lock.
				mAdapter.notifyDataSetChanged();
				mLockListView = false;
			}
		};
		
		Handler handler = new Handler();
		handler.postDelayed(run, 5000);
	}
	
}
